package com.xsherl.leetcode.solution;

import cn.hutool.core.lang.Assert;
import com.xsherl.leetcode.base.ListNode;

public class RemoveNthFromEnd {

    /**
     *  滑动窗口，固定窗口为 n, 由题可知,当到达链表尾部时，移除窗口最开始的元素
     *
     * @param head
     *  链表中结点的数目为 sz
     * 1 <= sz <= 30
     * 0 <= Node.val <= 100
     * @param n
     * 1 <= n <= sz
     */
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode nPre = new ListNode(-1, head), tail = head;
        int c = 0;
        while (tail != null){
            if (c >= n){
                nPre = nPre.next;
            }
            tail = tail.next;
            c++;
        }
        if (nPre.next == head){
            head = head.next;
        } else {
            nPre.next = nPre.next.next;
        }
        return head;
    }

    public static void main(String[] args) {
        int[] nums = {1,2, 3, 4, 5};
        int k = 1;
        ListNode root = ListNode.build(nums);
        ListNode listNode = new RemoveNthFromEnd().removeNthFromEnd(root, k);
        System.out.println(listNode);
//        int[] outPut = {1,2,3,5};
//        Assert.isTrue(ListNode.build(outPut).equals(listNode));
    }

}
